package com.tsystems.train.bean;

import java.io.Serializable;

import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Named;

import com.tsystems.train.entity.User;
import com.tsystems.train.entity.UserRoles;
import com.tsystems.train.service.UserServices;

@Named("userBean")
@SessionScoped
public class UserBean implements Serializable {

	private static final long serialVersionUID = 2165793273424547096L;

	@EJB
	private UserServices userService;

	private String login;
	private String password;

	public UserBean() {
		
	}
	
	public String athorizate() {
		String result=userService.login(login, password);
		if (result.equals("Login executed successfully")) {
			FacesContext.getCurrentInstance().addMessage(null, 
					 new FacesMessage("Welcome \"" + login + "\"!"));
			
			 
			return "index?faces-redirect=true";
		} else {
			FacesContext.getCurrentInstance().addMessage(null,
					 new FacesMessage(FacesMessage.SEVERITY_ERROR, result, null));
			return null;
		}
	}
	
	public boolean isLoggedIn() {
		return login != null;
	}
	
	public String getRole() {
	    User user=userService.getUser(login);
	    
		return user==null ? UserRoles.DEFAULT.toString() : user.getRole().toString();
	}

	public String getLogin() {
		return login;
	}

	public void setLogin(String login) {
		this.login = login;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
}
